package net.ib.mtalk.ui.buddy.info;

import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.UUID;

import net.ib.mntalk.protocol.Common;
import net.ib.mntalk.protocol.Common.BuddyInfo;
import net.ib.mntalk.protocol.Common.Calendar;
import net.ib.mntalk.protocol.Common.UserAccessControl;
import net.ib.mntalk.protocol.Session.SetBuddyInfoReq;
import net.ib.mtalk.R;
import net.ib.mtalk.base.BaseActivity;
import net.ib.mtalk.constant.HandlerMsgConst;
import net.ib.mtalk.database.DatabaseContract.BuddyTable;
import net.ib.mtalk.database.DatabaseContract.GroupTable;
import net.ib.mtalk.database.DatabaseContract.MessageTable;
import net.ib.mtalk.database.DatabaseContract.ParticipantsTable;
import net.ib.mtalk.database.helper.ParticipantsDatabaseHelper;
import net.ib.mtalk.ui.buddy.item.BuddyProfileItem;
import net.ib.mtalk.ui.inbox.InboxController;
import net.ib.mtalk.util.GpbSupport;
import net.ib.mtalk.util.MTalkLogWriter;
import net.ib.mtalk.util.ProfileImageLoader;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.protobuf.micro.InvalidProtocolBufferMicroException;

public class BuddyInfoActivity extends BaseActivity implements OnClickListener, OnItemClickListener{
	
	public static final int BLOCK = 1;
	public static final int REMOVE = 2;

	private Context mContext;
	private BuddyInfoController mUiController;
	private InboxController inboxController;
	
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch(msg.what){
			case HandlerMsgConst.HANDLER_BLOCK_BUDDY_SUCCESS:
				Toast.makeText(mContext, "HANDLER_BLOCK_BUDDY_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_BLOCK_BUDDY_FAIL:
				Toast.makeText(mContext, "HANDLER_BLOCK_BUDDY_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_REMOVE_BUDDY_SUCCESS:
				Toast.makeText(mContext, "HANDLER_REMOVE_BUDDY_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_REMOVE_BUDDY_FAIL:
				Toast.makeText(mContext, "HANDLER_REMOVE_BUDDY_FAIL", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_UNKNOWN_ERROR:
				Toast.makeText(mContext, "HANDLER_UNKNOWN_ERROR", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_INSERT_FAVORITE_SUCCESS:
				Toast.makeText(mContext, "INSERT_FAVORITE_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_REMOVE_FAVORITE_SUCCESS:
				Toast.makeText(mContext, "REMOVE_FAVORITE_SUCCESS", Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_USER_ACCESSCONTROL_SUCCESS:
				UserAccessControl control = (UserAccessControl) msg.obj;
				Toast.makeText(mContext, "HANDLER_GET_USER_ACCESSCONTROL_SUCCESS status : " + control.getStatusAcl(), Toast.LENGTH_SHORT).show();
				break;
			case HandlerMsgConst.HANDLER_GET_USER_ACCESSCONTROL_FAIL:
				Toast.makeText(mContext, "HANDLER_GET_USER_ACCESSCONTROL_FAIL", Toast.LENGTH_SHORT).show();
				break;
			}
		};
	};
	
	Bundle extras;
	static int buddy_id;
	static String uuid_msb;
	static String uuid_lsb;
	private String buddyNick;
	private String buddyName;
	private String buddyStatus;
	private Calendar buddyCalendar;
	private ImageView bi_image;
	private TextView bi_Name;
	private TextView bi_Status;
	private TextView bi_Birthday;
	private TextView bi_Birthday_count;
	private TextView groupdetail;
	private Button bi_Mainbtn;
	
	private BuddyInfo buddyInfo = null;
	private String[] groupNames;
	private boolean[] mSelect;
	private List<Integer> groupIDs = new ArrayList<Integer>();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_buddy_info);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
		mContext = this;
		
		mUiController = new BuddyInfoController(mContext, mHandler);
		inboxController = new InboxController(mContext, mHandler);
		
		extras = getIntent().getExtras();
		if (extras != null) {
			buddy_id = extras.getInt(BuddyTable._ID);
			uuid_msb = extras.getString(BuddyTable.KEY_BUDDY_UUID_MSB);
			uuid_lsb = extras.getString(BuddyTable.KEY_BUDDY_UUID_LSB);
			try {
				buddyInfo = BuddyInfo.parseFrom(extras.getByteArray(BuddyTable.KEY_BUDDY_INFO));
			} catch (InvalidProtocolBufferMicroException e) {
				e.printStackTrace();
			}
		}
		
		initialView();
		
		ProfileImageLoader.getInstance(mContext).loadProfileImage(bi_image, 
				GpbSupport.UuidMsgToString(GpbSupport.makeUuidMsg(Long.valueOf(uuid_msb), Long.valueOf(uuid_lsb))));
		
		ListAdapter mAdapter = new BuddyInfoAdapter(mContext, uuid_msb , uuid_lsb);
		
		ListView listView = addFooterView();
		listView.setAdapter(mAdapter);
		
		listView.setOnItemClickListener(this);
		
//		mUiController.getAccessControl(new Session.GetUserAccessControlReq().addProperty(Common.USER_PROPERTY_NAME)
//																			.addProperty(Common.USER_PROPERTY_PROFILE_IMAGE)
//																			.addProperty(Common.USER_PROPERTY_GENDER)
//																			.addProperty(Common.USER_PROPERTY_BIRTHDAY)
//																			.addProperty(Common.USER_PROPERTY_BIO)
//																			.addProperty(Common.USER_PROPERTY_PRESENCE)
//																			.addProperty(Common.USER_PROPERTY_STATUS)
//																			.addProperty(Common.USER_PROPERTY_LOCATION)
//																			.addProperty(Common.USER_PROPERTY_MOOD)
//		);
	}

	private ListView addFooterView() {
		View footerView = getLayoutInflater().inflate(R.layout.list_item_group, null, true);
		RelativeLayout relativeLayout = (RelativeLayout) footerView.findViewById(R.id.list_item_group);
		relativeLayout.setOnClickListener(this);
		groupdetail = (TextView) footerView.findViewById(R.id.groupdetail);
		
		String selection = ParticipantsTable.KEY_PARTICIPANTS_BUDDY + "=?";
		Cursor personal_cursor1 = mContext.getContentResolver().query(GroupTable.buildBuddyInfoUri(), null, selection, 
								new String[]{String.valueOf(buddy_id)}, GroupTable.KEY_GROUP_NAME);
		String text = "";
		try{
			while(personal_cursor1.moveToNext()){
				if(!text.equals("")){
					text += ", ";
				}
				text += personal_cursor1.getString(personal_cursor1.getColumnIndexOrThrow(GroupTable.KEY_GROUP_NAME));
			}
		} finally {
			personal_cursor1.close();
		}
		if(text.equals("")){
			groupdetail.setText(getString(R.string.group_not_assigned));
		} else{
			groupdetail.setText(text);
		}
		
		ImageView imgbtn = (ImageView) footerView.findViewById(R.id.imgbtnGroup);
		imgbtn.setOnClickListener(this);
		ListView listView = (ListView) findViewById(R.id.bi_list);
		footerView.setSelected(true);
		footerView.setFocusable(true);
		footerView.setClickable(true);
		
		listView.addFooterView(footerView, null, true);
		return listView;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		
		menu.add(0, BLOCK, 0, R.string.buddy_talk_Block).setIcon(R.drawable.menu_icon_cutoff);
		menu.add(0, REMOVE, 0, R.string.buddy_talk_Remove).setIcon(R.drawable.menu_icon_del);
		
		return true;
	}
	
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		if(item.getItemId() == BLOCK){
			SetBuddyInfoReq setBuddyInfoReq = new SetBuddyInfoReq();
			buddyInfo.setBuddyStatus(Common.BUDDY_STATUS_BLOCK);
			setBuddyInfoReq.setBuddyInfo(buddyInfo);
			setBuddyInfoReq.addProperty(Common.BUDDY_STATUS);
			mUiController.blockBuddy(setBuddyInfoReq);
		} else if(item.getItemId() == REMOVE){
			SetBuddyInfoReq setBuddyInfoReq = new SetBuddyInfoReq();
			buddyInfo.setBuddyStatus(Common.BUDDY_STATUS_DELETE);
			setBuddyInfoReq.setBuddyInfo(buddyInfo);
			setBuddyInfoReq.addProperty(Common.BUDDY_STATUS);
			mUiController.removeBuddy(setBuddyInfoReq);
		}
		finish();
		return super.onMenuItemSelected(featureId, item);
	}

	private void initialView() {
		bi_image = (ImageView) findViewById(R.id.bi_image);
		bi_Name = (TextView) findViewById(R.id.bi_Name);
		bi_Status = (TextView) findViewById(R.id.bi_Status);
		bi_Birthday = (TextView) findViewById(R.id.bi_Birthday);
		bi_Birthday_count = (TextView) findViewById(R.id.bi_Birthday_count);
		bi_Mainbtn = (Button) findViewById(R.id.bi_Mainbtn);
		
		MTalkLogWriter.d(new UUID(Long.parseLong(uuid_msb), Long.parseLong(uuid_lsb)).toString() + "");
		
		String select = "((" + BuddyTable.KEY_BUDDY_UUID_MSB + "=?) AND (" + BuddyTable.KEY_BUDDY_UUID_LSB + "=?))"; 
		String[] selectionArgs = new String[] {uuid_msb, uuid_lsb};
		Cursor cursor = getContentResolver().query(BuddyTable.CONTENT_URI, BuddyTable.PROJECTION, select, selectionArgs, null);
		
		BuddyInfo buddyInfo = null;
		try{
			while (cursor.moveToNext()) {
				buddyInfo = BuddyInfo.parseFrom(cursor.getBlob(cursor.getColumnIndex(BuddyTable.KEY_BUDDY_INFO)));
				buddyName = cursor.getString(cursor.getColumnIndex(BuddyTable.KEY_BUDDY_DISPLAYNAME));
				buddyNick = cursor.getString(cursor.getColumnIndex(BuddyTable.KEY_BUDDY_DISPLAYNICK));
				buddyStatus = buddyInfo.getProfile().getStatus();
				buddyCalendar = buddyInfo.getProfile().getBirthday();
			}
		} catch (InvalidProtocolBufferMicroException e) {
			e.printStackTrace();
		} finally {
			cursor.close();
		}
		bi_Name.setText(buddyNick);
		bi_Status.setText(buddyStatus);
		if(buddyCalendar != null && !buddyCalendar.equals("") 
				&& buddyCalendar.getYear() != -1 && buddyCalendar.getMonth() != -1 && buddyCalendar.getDay() != -1){
			String birth = changeDate(buddyCalendar.getYear(), buddyCalendar.getMonth(), buddyCalendar.getDay());
			bi_Birthday.setText(birth);
			birthCount();
		}
		bi_Mainbtn.setOnClickListener(this);
	}

	private void birthCount() {
		GregorianCalendar now_calendar = new GregorianCalendar();
		GregorianCalendar birth_calendar = new GregorianCalendar();
		
		birth_calendar.set(java.util.Calendar.MONTH, buddyCalendar.getMonth()-1);
		birth_calendar.set(java.util.Calendar.DAY_OF_MONTH, buddyCalendar.getDay());

		GregorianCalendar before_calendar =  new GregorianCalendar();
		before_calendar.set(java.util.Calendar.MONTH, buddyCalendar.getMonth()-1);
		before_calendar.set(java.util.Calendar.DAY_OF_MONTH, buddyCalendar.getDay());

		before_calendar.add(java.util.Calendar.DAY_OF_MONTH, - 7);
		
		
		int temp = now_calendar.get(java.util.Calendar.DAY_OF_MONTH) - theLastDay(now_calendar.get(java.util.Calendar.YEAR), now_calendar.get(java.util.Calendar.MONTH)) - birth_calendar.get(java.util.Calendar.DAY_OF_MONTH);
		if((!birth_calendar.before(now_calendar) && birth_calendar.after(before_calendar)) ||
				((now_calendar.get(java.util.Calendar.MONTH) == 12 && birth_calendar.get(java.util.Calendar.MONTH) == 1) &&
						temp > -8 && temp < 0)){
			int dday = now_calendar.get(java.util.Calendar.DAY_OF_MONTH) - birth_calendar.get(java.util.Calendar.DAY_OF_MONTH);
			// 7일 전 일 경우만 보여준다.
			if(dday == 0 && birth_calendar.get(java.util.Calendar.MONTH) == now_calendar.get(java.util.Calendar.MONTH)){
				bi_Birthday_count.setText("(D-Day)");
			} else if(dday < 0 && dday > -8 && birth_calendar.get(java.util.Calendar.MONTH) == now_calendar.get(java.util.Calendar.MONTH)){
				bi_Birthday_count.setText("(D" + dday + ")");
			} else if(((birth_calendar.get(java.util.Calendar.DAY_OF_MONTH) - now_calendar.get(java.util.Calendar.DAY_OF_MONTH)) < -8) && temp > -8 && temp < 0
					   && birth_calendar.get(java.util.Calendar.MONTH) == now_calendar.get(java.util.Calendar.MONTH) + 1){
				bi_Birthday_count.setText("(D" + temp + ")");
			} else{
				return;
			}
			bi_Birthday_count.setVisibility(View.VISIBLE);
		}
	}
	
	// 말일 구하기
	private int theLastDay(int year, int month){
		int lastDay = 30;
		if(month == 1){
			if(leapYearTF(year)) lastDay = 29;
			else lastDay = 28;
		} else if(month % 2 == 0){
			lastDay = 31;
		}
		return lastDay;
	}
	
	// 윤달체크
	private boolean leapYearTF(int year){
		boolean leapTF = false;
		if((year % 4 == 0) && (year % 100 != 0)||(year % 400 == 0)){
			leapTF = true;
		}
		return leapTF;
	}

	private String changeDate(int year, int month, int day) {
		String mMonth = "";
		switch (month) {
		case 1:
			mMonth = "Jan";
			break;
		case 2:
			mMonth = "Feb";
			break;
		case 3:
			mMonth = "Mar";
			break;
		case 4:
			mMonth = "Apr";
			break;
		case 5:
			mMonth = "May";
			break;
		case 6:
			mMonth = "Jun";
			break;
		case 7:
			mMonth = "Jul";
			break;
		case 8:
			mMonth = "Aug";
			break;
		case 9:
			mMonth = "Sep";
			break;
		case 10:
			mMonth = "Oct";
			break;
		case 11:
			mMonth = "Nov";
			break;
		case 12:
			mMonth = "Dec";
			break;
		default:
			break;
		}
		return mMonth + " " + day + ", " + year;
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
			case R.id.bi_Mainbtn:
				inboxController.startOneToOneChat(Long.valueOf(uuid_msb), Long.valueOf(uuid_lsb), buddyName);
				break;
			
			case R.id.list_item_group:
			case R.id.imgbtnGroup:
				String selection = GroupTable._ID + ">'2'";	// not assinged group 은 보이지 않음.
				Cursor cursor5 = mContext.getContentResolver().query(GroupTable.CONTENT_URI, null, selection, null, GroupTable.KEY_GROUP_NAME);
				if(cursor5.getCount() == 0){
					cursor5.close();
					Toast.makeText(mContext, R.string.buddy_no_group, Toast.LENGTH_SHORT).show();
					break;
				} else{
					groupNames = new String[cursor5.getCount()];
					mSelect = new boolean[cursor5.getCount()];
					try{
						while(cursor5.moveToNext()){
							groupNames[cursor5.getPosition()] = cursor5.getString(cursor5.getColumnIndexOrThrow(GroupTable.KEY_GROUP_NAME));
							groupIDs.add(cursor5.getInt(cursor5.getColumnIndexOrThrow(GroupTable._ID)));
						}
					} finally {
						cursor5.close();
					}
				}
				
				Cursor cursor = mContext.getContentResolver().query(ParticipantsTable.buildBuddyGroupUri(), null, null, null, null);
				try{
					while(cursor.moveToNext()){
						long  msb = cursor.getLong(cursor.getColumnIndexOrThrow("a." + BuddyTable.KEY_BUDDY_UUID_MSB));
						long  lsb = cursor.getLong(cursor.getColumnIndexOrThrow("a." + BuddyTable.KEY_BUDDY_UUID_LSB));
						if(uuid_msb.equals(msb+"") && uuid_lsb.equals(lsb+"")){
							int groupId = cursor.getInt(cursor.getColumnIndexOrThrow("b." + ParticipantsTable.KEY_PARTICIPANTS_GROUP));
							mSelect[groupIDs.indexOf(groupId)] = true;
						}
					}
				} finally {
					cursor.close();
				}
				
				AlertDialog.Builder builder5 = new AlertDialog.Builder(mContext);
				builder5.setTitle(R.string.buddy_select_group);
				builder5.setMultiChoiceItems(groupNames, mSelect, MutiChoiceListener());
				builder5.setPositiveButton(R.string.ok, okListener());
				builder5.setNegativeButton(R.string.cancel, null);
				builder5.show();
				break;
		}
		
	}
	
	private DialogInterface.OnClickListener okListener(){
		DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				String text ="";
				for(int i = 0; i < mSelect.length; i++){
					if(mSelect[i]){
						ParticipantsDatabaseHelper.insert(mContext, buddy_id, groupIDs.get(i));
						if(!text.equals("")){
							text += ", ";
						}
						text += groupNames[i];
					} else{
						ParticipantsDatabaseHelper.delete(mContext, buddy_id, groupIDs.get(i));
					}
				}
				if(text.equals("")){
					groupdetail.setText("Not Assigned");
				} else {
					groupdetail.setText(text);
				}
			}
		};
		return listener;
	}

	private OnMultiChoiceClickListener MutiChoiceListener() {
		OnMultiChoiceClickListener listener = new DialogInterface.OnMultiChoiceClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which, boolean isChecked) {
				mSelect[which] = isChecked;
			}
		};
		return listener;
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		BuddyProfileItem item = (BuddyProfileItem) adapterView.getItemAtPosition(position);
		if(item.Type == 0) {
			Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + item.phoneNumber));
			startActivity(intent);
		} else if(item.Type == 1){
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/email");
			intent.putExtra(Intent.EXTRA_EMAIL, new String[]{item.emailAddress});
			startActivity(intent);
		}
	}
}
